package com.wh.wisdomsite.xbox.server.controller.wo;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.pojo.wo.attend.*;
import com.wh.wisdomsite.xbox.pojo.wo.attendDetail.AttendDetailIn;
import com.wh.wisdomsite.xbox.pojo.wo.attendDetail.AttendDetailOut;
import com.wh.wisdomsite.xbox.pojo.wo.attendDetail.PersonCountArray;
import com.wh.wisdomsite.xbox.pojo.wo.groupInfo.GroupInfoOut;
import com.wh.wisdomsite.xbox.pojo.wo.groupInfo.GroupListOut;
import com.wh.wisdomsite.xbox.pojo.wo.repairCard.RepairStatistics;
import com.wh.wisdomsite.xbox.pojo.wo.workerInfo.WorkerDetail;
import com.wh.wisdomsite.xbox.pojo.wo.workerInfo.WorkerInfoOut;
import com.wh.wisdomsite.xbox.pr.entity.Project;
import com.wh.wisdomsite.xbox.pr.service.IProjectService;
import com.wh.wisdomsite.xbox.server.util.DateUtils;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.utils.Const;
import com.wh.wisdomsite.xbox.utils.IDCardUtils;
import com.wh.wisdomsite.xbox.utils.StringUtils;
import com.wh.wisdomsite.xbox.utils.server.connToserver_HttpClientClose;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 考勤controller
 * @author 刘旭
 * @version V1.0
 * @Package com.wh.wisdomsite.xbox.server.controller.wo
 * @date 2018年09月21日 9:25
 * @Copyright 企业版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
@Controller
@RequestMapping(value = "/attend")
public class AttendController {
    private static final Log logger = LogFactory.getLog(AttendController.class);

    @Autowired
    private IProjectService iProjectService;

    private static final Map<Integer, String> timeMap;
    static {
        timeMap = new HashMap<>();
        timeMap.put(1, "一月");
        timeMap.put(2, "二月");
        timeMap.put(3, "三月");
        timeMap.put(4, "四月");
        timeMap.put(5, "五月");
        timeMap.put(6, "六月");
        timeMap.put(7, "七月");
        timeMap.put(8, "八月");
        timeMap.put(9, "九月");
        timeMap.put(10, "十月");
        timeMap.put(11, "十一月");
        timeMap.put(12, "十二月");
    }

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 跳转到考勤信息
     *
     * @return
     */
    @RequiresPermissions("rules:wo_attend_page")
    @RequestMapping(value = "/index.do", method = RequestMethod.GET)
    public String index(HttpServletRequest request,String prId) {
        request.setAttribute("prId",prId);
        return "wo/attend/attendList";
    }

    /**
     * 获取考勤列表
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:wo_attend_find")
    @RequestMapping(value = "/attendList.do")
    public void attendList(HttpServletResponse response, AttendIn in) {
        logger.info("加载考勤列表-->>开始");
        try {
            if (in.getPage() == 0) in.setPage(1);
            if (in.getRows() == 0) in.setRows(10);
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            int total = 0;
            //历史登记施工人数
            Integer historyPersonCount = 0;
            //今日出勤人数
            Integer todayAttendanceCount = 0;
            //离职人数
            Integer quitedPersonCount = 0;
            String projectName = "";
            Project project = iProjectService.selectById(in.getProjectId());
            if (null != project) {
                projectName = project.getPrName();
            }
            //传入查询条件
            Map<String, String> map = new HashMap<String, String>();
            map.put("pageNumber", String.valueOf(in.getPage()));
            map.put("pageSize", String.valueOf(in.getRows()));
            map.put("projectIds", in.getProjectId());
            if(StringUtils.isNotEmpty(in.getUserName())){
                map.put("userName", in.getUserName());
            }
            if(StringUtils.isNotEmpty(in.getDeleted())){
                map.put("deleted", in.getDeleted());
            }
            //接口查询结果
            String result = connToserver_HttpClientClose.sendPostRequest(Const.WORKER_ATTENDMANAGERURL, map);
            if(result.contains("projectId")){
                result = result.replaceAll("Work","work").replaceAll("Group","group").replaceAll("null","\"\"");
            }
            //对象中存在集合的需要通过map注明集合的类型，否则会报错
            Map classMap = new HashMap();
            classMap.put("personMessage", PersonMessage.class);
            classMap.put("workCountArray", WorkCount.class);
            net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
            AttendOut attend = (AttendOut)net.sf.json.JSONObject.toBean(jsonObject, AttendOut.class,classMap);
            if(null != attend.getAttendCount().getTotalCount()){
                total = attend.getAttendCount().getTotalCount();
                historyPersonCount = attend.getAttendCount().getHistoryPersonCount();
                todayAttendanceCount = attend.getAttendCount().getTodayAttendanceCount();
                quitedPersonCount = attend.getAttendCount().getQuitedPersonCount();
            }
            //获取人员信息
            List<PersonMessage> personMessages = attend.getAttendCount().getPersonMessage();
            for(PersonMessage personMessage : personMessages){
                JSONObject jsonObj = new JSONObject(personMessage);
                WorkerInfoOut person = personMessage.getPerson();
                String idCard = person.getIdCard();
                //获取年龄
                Integer age = null;
                if(idCard.length() > 15){
                    Map<String, Object> mapCard = IDCardUtils.getCarInfo(idCard);
                    age = (Integer) mapCard.get("age");
                }else{
                    Map<String, Object> mapCard = IDCardUtils.getCarInfo15W(idCard);
                    age = (Integer) mapCard.get("age");
                }
                String createTime = person.getCreatedAt();
                String joinProjectTime = DateUtils.dateStrChangeToTime(createTime);
                jsonObj.put("joinProjectTime",joinProjectTime);
                jsonObj.put("age",age);
                jsonObj.put("sex",person.getSex());
                jsonObj.put("groupName",person.getGroup().getName());
                jsonObj.put("projectName",projectName);
                jsonObj.put("headImg",person.getHeadImg());
                array.put(jsonObj);
            }
            json.put("historyPersonCount", historyPersonCount);
            json.put("todayAttendanceCount", todayAttendanceCount);
            json.put("quitedPersonCount", quitedPersonCount);
            json.put("total", total);
            json.put("rows", array);
            ResManager.getJsonOut(response).print(json);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取考勤列表-->Exception " + e.getMessage());
        }
    }

    /**
     * 跳转考勤详细信息列表
     * @param request
     * @param in
     * @return
     */
    @RequiresPermissions("rules:wo_attend_view")
    @RequestMapping(value = "/toAttendDetailInfo.do")
    public String toAttendDetailInfo(HttpServletRequest request, AttendDetailIn in) {
        Map dateMap = getAttendDetailDate(in);
        String headImg = workerImg(in);
        String workerDays = (String)dateMap.get("workerDays");
        String totalAttendLength = (String)dateMap.get("totalAttendLength");
        String supplementCard = (String)dateMap.get("supplementCard");
        List<Map<String,String>> timeList = (List<Map<String,String>>)dateMap.get("timeList");
        WorkerInfoOut workerInfo = (WorkerInfoOut)dateMap.get("workerInfo");
        String currentMonth = (String)dateMap.get("currentMonth");
        request.setAttribute("workerDays",workerDays);
        request.setAttribute("totalAttendLength",totalAttendLength);
        request.setAttribute("supplementCard",supplementCard);
        request.setAttribute("timeList",timeList);
        request.setAttribute("workerInfo",workerInfo);
        request.setAttribute("currentMonth",currentMonth);
        request.setAttribute("personInfo",in);
        request.setAttribute("headImg",headImg);
        return "wo/attend/attendDetailInfo";
    }


    /**
     * 获取人员头像
     * @param in
     * @return
     */
    public String workerImg(AttendDetailIn in){
        logger.info("加载农名工信息-->>开始");
        String idCard = in.getIdCard();
        String projectId = in.getProjectId();
        String headImg = "";
        try{
            if(StringUtils.isNotEmpty(idCard) && StringUtils.isNotEmpty(projectId)){
                Map<String, String> map = new HashMap<String, String>();
                map.put("idCard", idCard);
                map.put("projectId", projectId);
                String result = connToserver_HttpClientClose.sendPostRequest(Const.WORKER_PERSONMSGURL, map);
                if(result.contains("idCard")){
                    result = result.replaceAll("Work","work").replaceAll("Group","group").replaceAll("null","\"\"");
                }
                net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
                WorkerDetail workerDetail = (WorkerDetail)net.sf.json.JSONObject.toBean(jsonObject, WorkerDetail.class);
                if(null != workerDetail){
                    WorkerInfoOut worker = workerDetail.getResolve();
                    headImg = worker.getHeadImg();
                }
            }
            logger.info("加载农名工信息-->>开始");
        }catch (Exception e){
            e.printStackTrace();
            logger.error("加载农名工信息->>getUsers->>Exception " + e.getMessage());
        }
        return headImg;
    }

    /**
     * 查询考勤详细信息
     * @param response
     * @param in
     * @return
     */
    @RequestMapping(value = "/getAttendDetailInfo.do")
    public void getAttendDetailInfo(HttpServletResponse response, AttendDetailIn in) {
        Map dateMap = getAttendDetailDate(in);
        String workerDays = (String)dateMap.get("workerDays");
        String totalAttendLength = (String)dateMap.get("totalAttendLength");
        String supplementCard = (String)dateMap.get("supplementCard");
        List<Map<String,String>> timeList = (List<Map<String,String>>)dateMap.get("timeList");
        JSONObject json = new JSONObject();
        try{
            json.put("workerDays",workerDays);
            json.put("totalAttendLength",totalAttendLength);
            json.put("supplementCard",supplementCard);
            json.put("timeList",timeList);
        }catch (Exception e){
            e.printStackTrace();
        }
        ResManager.getJsonOut(response).print(json);
    }
    
    

    /**
     * 获取考勤详情数据
     * @param in
     * @return
     */
    public Map getAttendDetailDate(AttendDetailIn in){

        //创建返回的数据map
        Map dataMap = new HashMap();
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH)+1;
        int day = cal.get(Calendar.DATE);
        String monthStr = getStrValue(month);
        String dayStr = getStrValue(day);
        //设置默认本月第一天时间
        String startTime = year + "-" + monthStr + "-01 00:00:00";
        //设置默认本月当天时间
        String endTime = year + "-" + monthStr + "-" + dayStr +" 23:59:59";

        String idCard = in.getIdCard();
        String projectId = in.getProjectId();
        if(StringUtils.isNotEmpty(in.getStartTime())){
            startTime = in.getStartTime() + " 00:00:00";
        }
        if(StringUtils.isNotEmpty(in.getEndTime())){
            endTime = in.getEndTime() + " 23:59:59";
        }
        //出勤、补卡时间
        List<Map<String,String>> timeList = new ArrayList<>();
        WorkerInfoOut workerInfo = new WorkerInfoOut();
        String workerDays = "";
        String totalAttendLength = "";
        //补卡天数
        String supplementCard = "";
        try {
            //身份证号及项目id不为空时做查询
            if (StringUtils.isNotEmpty(idCard) && StringUtils.isNotEmpty(projectId) || 1==1) {
                //查询条件
                Map<String, String> map = new HashMap<String, String>();
                map.put("idCard", idCard);
                map.put("projectId", projectId);
                map.put("startTime", startTime);
                map.put("endTime", endTime);
                //接口查询结果
                String result = connToserver_HttpClientClose.sendPostRequest(Const.WORKER_ATTENDMANAGERDETAILURL, map);
                if(result.contains("projectId")){
                    result = result.replaceAll("Work","work").replaceAll("Group","group").replaceAll("null","\"\"");
                }
                //对象中存在集合的需要通过map注明集合的类型，否则会报错
                Map classMap = new HashMap();
                classMap.put("persons", PersonCountArray.class);
                classMap.put("punchTimes", String.class);
                classMap.put("repairCardObj", RepairStatistics.class);
                net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
                AttendDetailOut attendDetailList = (AttendDetailOut)net.sf.json.JSONObject.toBean(jsonObject, AttendDetailOut.class,classMap);
                //获取人员基本信息
                if(attendDetailList.getPersonCount().getPersons().size() > 0){
                    workerInfo = attendDetailList.getPersonCount().getPersons().get(0).getPerson();
                }
                if(null != workerInfo.getCreatedAt()){
                    String createDate = DateUtils.dateStrChangeToTime(workerInfo.getCreatedAt());
                    workerInfo.setCreatedAt(createDate);
                }
                //获取出勤天数
                workerDays = attendDetailList.getPersonCount().getWorkDays() + "";
                //获取出勤时长
                totalAttendLength = attendDetailList.getPersonCount().getTotalAttendLength() + "";
                //人员信息集合
                List<PersonCountArray> personCountArray = attendDetailList.getPersonCount().getPersons();
                //补卡信息集合
                List<RepairStatistics> repairStatisticsList = attendDetailList.getPersonCount().getRepairCardObj();
                supplementCard = String.valueOf(repairStatisticsList.size());
                for(PersonCountArray personCount : personCountArray){
                    //出勤时间
                    String attendTime = personCount.getAttendDate();
                    //构造页面中出勤及补卡时间日历
                    if(StringUtils.isNotEmpty(attendTime)){
                        Long longStart = DateUtils.getLongTime(attendTime + " 00:00:00");
                        Long longEnd = DateUtils.getLongTime(attendTime + " 23:59:59");
                        Map<String,String> timeMap = new HashMap<>();
                        timeMap.put("id",attendTime);
                        timeMap.put("title","正常出勤");
                        timeMap.put("classTemp","event-info");
                        timeMap.put("start",String.valueOf(longStart));
                        timeMap.put("end",String.valueOf(longEnd));
                        //出勤时间中有补卡的将出勤替换为补卡
                        int repairStatisticsCount = repairStatisticsList.size();
                        for(int i=0; i<repairStatisticsCount; i++){
                            RepairStatistics repairStatistics = repairStatisticsList.get(i);
                            String cardRepairDate = repairStatistics.getCardRepairDate();
                            if(attendTime.equals(cardRepairDate)){
                                timeMap.put("title","补卡");
                                timeMap.put("classTemp","event-warning");
                                repairStatisticsList.remove(i);
                                i--;
                                repairStatisticsCount--;
                            }
                        }
                        timeList.add(timeMap);
                    }
                }
                //存在整天都缺卡的情况
                for(RepairStatistics repairStatistics : repairStatisticsList){
                    String cardRepairDate = repairStatistics.getCardRepairDate();
                    Long longStart = DateUtils.getLongTime(cardRepairDate + " 00:00:00");
                    Long longEnd = DateUtils.getLongTime(cardRepairDate + " 23:59:59");
                    Map<String,String> timeMap = new HashMap<>();
                    timeMap.put("id",cardRepairDate);
                    timeMap.put("title","补卡");
                    timeMap.put("classTemp","event-warning");
                    timeMap.put("start",String.valueOf(longStart));
                    timeMap.put("end",String.valueOf(longEnd));
                    timeList.add(timeMap);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取考勤详细信息列表-->Exception " + e.getMessage());
        }
        dataMap.put("workerDays",workerDays);
        dataMap.put("totalAttendLength",totalAttendLength);
        dataMap.put("supplementCard",supplementCard);
        dataMap.put("timeList",timeList);
        dataMap.put("workerInfo",workerInfo);
        dataMap.put("currentMonth",timeMap.get(month));
        return dataMap;
    }

    /**
     * 获取人员具体信息
     * @param request
     * @param idCard
     * @param projectName
     * @return
     */
    @RequiresPermissions("rules:wo_attend_detail")
    @RequestMapping(value = "/attendPersonDetail.do")
    public String attendPersonDetail(HttpServletRequest request,String idCard,String projectName,String projectId){
        logger.info("获取人员信息-->>开始");
        //创建人员详情对象
        WorkerDetail workerDetail = new WorkerDetail();
        //年龄
        Integer age = null;
        //创建时间
        String createDate = null;
        //有效时间
        Integer effectiveTime = null;
        try{
            if(StringUtils.isNotEmpty(idCard) && StringUtils.isNotEmpty(projectId)){
                //查询条件
                Map<String, String> map = new HashMap<String, String>();
                map.put("idCard", idCard);
                map.put("projectId", projectId);
                //接口查询结果
                String result = connToserver_HttpClientClose.sendPostRequest(Const.WORKER_PERSONMSGURL, map);
                if(result.contains("idCard")){
                    result = result.replaceAll("Work","work").replaceAll("Group","group").replaceAll("null","\"\"");
                }
                net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
                workerDetail = (WorkerDetail)net.sf.json.JSONObject.toBean(jsonObject, WorkerDetail.class);
                if(null != workerDetail){
                    WorkerInfoOut worker = workerDetail.getResolve();
                    worker.setProjectName(projectName);
                    // 获取年龄
                    String getIdCard = worker.getIdCard();
                    if(getIdCard.length() > 15){
                        Map<String, Object> mapCard = IDCardUtils.getCarInfo(getIdCard);
                        age = (Integer) mapCard.get("age");
                    }else{
                        Map<String, Object> mapCard = IDCardUtils.getCarInfo15W(getIdCard);
                        age = (Integer) mapCard.get("age");
                    }
                    // 创建时间
                    createDate = DateUtils.dateStrChangeToTime(worker.getCreatedAt());
                    // 有效期
                    String effectiveTimeSection = worker.getValidDay();
                    if(StringUtils.isNotEmpty(effectiveTimeSection)){
                        String[] timeArr = effectiveTimeSection.split("-");
                        String startTime = timeArr[0].replaceAll("\\.","-");
                        String endTime = timeArr[1].replaceAll("\\.","-");
                        Map dateMap = DateUtils.getApartTime(startTime,endTime);
                        if(null != dateMap){
                            effectiveTime = (Integer) dateMap.get("YEAR");
                        }
                    }
                }
            }
            logger.info("获取人员信息-->>开始");
        }catch (Exception e){
            e.printStackTrace();
            logger.error("获取人员信息->>getUsers->>Exception " + e.getMessage());
        }
        request.setAttribute("workerInfo",workerDetail.getResolve());
        request.setAttribute("age",age);
        request.setAttribute("createDate",createDate);
        request.setAttribute("effectiveTime",effectiveTime + 1);
        return "/wo/attend/attendPersonDetail";
    }


    /**
     * 首页获取劳务人员统计数据
     * @param response
     */
    @RequestMapping(value = "/workerStatistics.do")
    public void attendPersonDetail(HttpServletResponse response){
        JSONObject json = new JSONObject();
        //历史登记施工人数
        Integer historyPersonCount = 0;
        //今日出勤人数
        Integer todayAttendanceCount = 0;
        //离职人数
        Integer quitedPersonCount = 0;
        //班组数
        Integer groupCount = 0;
        //工种类别名称
        List<String> workNames = new ArrayList<>();
        //工种类别数量
        List<Integer> workTypeCounts = new ArrayList<>();
        try{
            EntityWrapper<Project> ewProject = new EntityWrapper<>();
            //若用户不是超级管理员根据用户的数据权限添加查询条件
            if (!UserUtils.isSysAdmin()) {
                ewProject = UserUtils.setEntityWrapper(ewProject, "c1", "o1", "p");
            }
            ewProject.setEntity(new Project());
            List<Project> projectList = iProjectService.selectList(ewProject);
            String projectIds = "";
            for (Project project : projectList){
                String projectId = project.getPrId();
                projectIds = projectIds + projectId + ",";
            }
            if(StringUtils.isNotEmpty(projectIds)){
                String projectIdsRel = projectIds.substring(0, projectIds.length() - 1);
                Map<String, String> map = new HashMap<String, String>();
                map.put("pageNumber", String.valueOf(1));
                map.put("pageSize", String.valueOf(10));
                map.put("projectIds", projectIdsRel);
                String result = connToserver_HttpClientClose.sendPostRequest(Const.WORKER_ATTENDMANAGERURL, map);
                if(result.contains("projectId")){
                    result = result.replaceAll("Work","work").replaceAll("Group","group").replaceAll("null","\"\"");
                }
                //对象中存在集合的需要通过map注明集合的类型，否则会报错
                Map classMap = new HashMap();
                classMap.put("personMessage", PersonMessage.class);
                classMap.put("workCountArray", WorkCount.class);
                net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
                AttendOut attend = (AttendOut)net.sf.json.JSONObject.toBean(jsonObject, AttendOut.class,classMap);
                if(null != attend.getAttendCount().getTotalCount()){
                    historyPersonCount = attend.getAttendCount().getHistoryPersonCount();
                    todayAttendanceCount = attend.getAttendCount().getTodayAttendanceCount();
                    quitedPersonCount = attend.getAttendCount().getQuitedPersonCount();
                    List<WorkCount> workCounts = attend.getAttendCount().getWorkCountArray();
                    for(WorkCount workCount : workCounts){
                        String workName = workCount.getWorkName();
                        Integer workTypeCount = workCount.getPersons();
                        workNames.add(workName);
                        workTypeCounts.add(workTypeCount);
                    }
                }
                //通过班组接口获取班组数
                String resultGroup = connToserver_HttpClientClose.sendPostRequest(Const.WORKER_GROUPPAGEURL, map);
                if(result.contains("projectId")){
                    resultGroup = resultGroup.replaceAll("Work","work").replaceAll("Group","group").replaceAll("null","\"\"");
                }
                Map classMapGroup = new HashMap();
                classMapGroup.put("groupObj", GroupInfoOut.class);
                net.sf.json.JSONObject jsonObjectGroup = net.sf.json.JSONObject.fromObject(resultGroup);
                GroupListOut groups = (GroupListOut)net.sf.json.JSONObject.toBean(jsonObjectGroup, GroupListOut.class,classMapGroup);
                groupCount = groups.getGroupsObj().getCount();

            }
            json.put("historyPersonCount", historyPersonCount);
            json.put("todayAttendanceCount", todayAttendanceCount);
            json.put("quitedPersonCount", quitedPersonCount);
            json.put("groupCount", groupCount);
            json.put("workNames", workNames);
            json.put("workTypeCounts", workTypeCounts);
            ResManager.getJsonOut(response).print(json);
            logger.info("获取劳务人员统计数据->>wh.zhgd.wo.worker.getWoStatistics->>结束");
        }catch (Exception e){
            logger.error("获取劳务人员统计数据->>wh.zhgd.wo.worker.getWoStatistics->>异常："+e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 跳转统计考勤信息
     *
     * @return
     */
    @RequiresPermissions("rules:wo_attend_statisticPage")
    @RequestMapping(value = "/statisticIndex.do", method = RequestMethod.GET)
    public String statisticIndex(HttpServletRequest request,String prId) {
        String prName = "";
        if(StringUtils.isNotEmpty(prId)){
            Project project = iProjectService.selectById(prId);
            prName = project.getPrName();
        }
        request.setAttribute("prId",prId);
        request.setAttribute("prName",prName);
        return "wo/attend/attendStatisticList";
    }

    /**
     * 查询考勤统计信息
     * @param response
     * @param in
     * @return
     */
    @RequiresPermissions("rules:wo_attend_statisticFind")
    @RequestMapping(value = "/attendStatisticInfo.do")
    public void attendStatisticInfo(HttpServletResponse response, AttendStatisticIn in) {
        JSONObject json = new JSONObject();
        try{
            logger.info("查询考勤统计信息列表-->>开始");
            //项目id
            String prId = in.getProjectId();
            //查询的时间范围
            String rangeTime = in.getRangeTime();
            //人员信息对象
            AttendPersonCountOut attendPersonCountOut = new AttendPersonCountOut();
            //获取开始时间与结束时间之间的日期范围集合
            List<String> dateList = new ArrayList<>();
            if(StringUtils.isNotEmpty(prId) && StringUtils.isNotEmpty(rangeTime)) {
                if (in.getPage() == 0) in.setPage(1);
                if (in.getRows() == 0) in.setRows(10);
                String[] rangeTimeArr = rangeTime.split(";");
                String startTime = rangeTimeArr[0];
                String endTime = rangeTimeArr[1];
                dateList = DateUtils.queryData(startTime,endTime);
                //查询条件
                Map<String, String> map = new HashMap<String, String>();
                map.put("projectId", prId);
                map.put("startTime", startTime + " 00:00:00");
                map.put("endTime", endTime + " 23:59:59");
                map.put("pageNumber", String.valueOf(in.getPage()));
                map.put("pageSize", String.valueOf(in.getRows()));
                if(StringUtils.isNotEmpty(in.getPersonName())){
                    map.put("name", in.getPersonName());
                }
                //接口查询结果
                String result = connToserver_HttpClientClose.sendPostRequest(Const.WORKER_ATTENDANCECOUNTBYPROJECTPERSONLIST, map);
                if (result.contains("idCard")) {
                    result = result.replaceAll("Work", "work").replaceAll("Group", "group").replaceAll("null","\"\"");
                }
                //对象中存在集合的需要通过map注明集合的类型，否则会报错
                Map classMap = new HashMap();
                classMap.put("personCountList", AttendPersonCount.class);
                classMap.put("persons", AttendPerson.class);
                classMap.put("repairCardObj", RepairStatistics.class);
                net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
                attendPersonCountOut = (AttendPersonCountOut) net.sf.json.JSONObject.toBean(jsonObject, AttendPersonCountOut.class,classMap);
            }
            JSONArray jsonArray = getStatisticData(attendPersonCountOut.getPersonAttendenceCountList(),dateList);
            json.put("rows",jsonArray);
            json.put("total", attendPersonCountOut.getPersonAttendenceCountList().getTotal());
            json.put("dateSize", dateList.size());
            ResManager.getJsonOut(response).print(json);
            logger.info("查询考勤统计信息列表-->>结束");
        }catch (Exception e){
            e.printStackTrace();
            logger.error("获取人员信息-->>Exception " + e.getMessage());
        }
    }


    /**
     * 提取需要的考勤统计数据
     * @param attendPersonCountOut
     * @return
     */
    public JSONArray getStatisticData(AttendPersonCountList attendPersonCountOut, List<String> dateList) throws Exception{
        JSONArray jsonArray = new JSONArray();
        //判断是否存在数据
        if(attendPersonCountOut.getPersonCountList().size() > 0){
            for(AttendPersonCount apc : attendPersonCountOut.getPersonCountList()){
                JSONObject object = new JSONObject();
                //人员名称
                String personName = apc.getName();
                //人员名称
                String workType = apc.getWorkType();
                object.put("personName",personName);
                object.put("workType",workType);
                //考勤信息
                List<AttendPerson> persons = apc.getPersons();
                //补卡
                List<RepairStatistics> repairCardObjs = apc.getRepairCardObj();
                //存储打卡记录时间
                Map<String,List<String>> attendDataMap = new HashMap<>();
                for(AttendPerson attendRecord : persons){
                    String attendDate = attendRecord.getAttendDate();
                    List<String> punchTimes = attendRecord.getPunchTimes();
                    if(punchTimes.size() > 0){
                        attendDataMap.put(attendDate,punchTimes);
                    }
                }
                //存储补卡记录
                Map<String,String> repairDataMap = new HashMap<>();
                for(RepairStatistics repair : repairCardObjs){
                    //补卡日期
                    String repairDate = repair.getCardRepairDate();
                    if(null == repair.getRepairStartDate() || null == repair.getRepairEndDate()){
                        continue;
                    }
                    //补卡开始结束时间
                    String repairStart = repair.getRepairStartDate().replaceAll(repairDate + " ","");
                    //补卡结束时间
                    String repairEnd = repair.getRepairEndDate().replaceAll(repairDate + " ","");
                    //补卡时间段
                    String rangeRepair = repairStart + "-" + repairEnd;
                    //如果存在同一天多个补卡时间段，则添加至repairDataMap
                    String repairExist = "";
                    if(null != repairDataMap.get(repairDate)){
                        repairExist = repairDataMap.get(repairDate);
                        repairExist = repairExist + "," + rangeRepair;
                    }else{
                        repairExist = rangeRepair;
                    }
                    repairDataMap.put(repairDate,repairExist);
                }
                //遍历时间范围获取打卡记录
                for(String date : dateList){
                    //当前日期号数
                    String currDate = date.substring(8);
                    int dateInt = Integer.valueOf(currDate);
                    //添加打卡记录
                    String times = "";
                    if(null != attendDataMap.get(date)){
                        List<String> dateRecordList = attendDataMap.get(date);
                        times = getDateRecord(dateRecordList,date);
                    }
                    //添加补卡记录
                    if(null != repairDataMap.get(date)){
                        if(StringUtils.isNotEmpty(times)){
                            times = times + "," + repairDataMap.get(date);
                        }else{
                            times = repairDataMap.get(date);
                        }
                    }
                    object.put("day" + dateInt,times);
                }
                jsonArray.put(object);
            }
        }
        return jsonArray;
    }


    /**
     * 获取当天对应的打卡记录,处理日期格式
     * @param dateRecordList
     * @param currDate
     * @return
     */
    public String getDateRecord(List<String> dateRecordList,String currDate){
        String dateRecord = "";
        StringBuilder sb = new StringBuilder();
        currDate = currDate + " ";
        for(String record : dateRecordList){
            String curRecord = record.replaceAll(currDate,"").replace("  ","-");
            sb.append(curRecord).append(",");
        }
        if(sb.length() > 0){
            dateRecord = sb.toString();
            dateRecord = dateRecord.substring(0,dateRecord.length() -1);
        }
        return dateRecord;
    }

    /**
     * 获取字符日期
     * @param value
     * @return
     */
    public String getStrValue(int value){
        String strValue = "";
        if(value < 10){
            strValue = "0" + String.valueOf(value);
        }else{
            strValue = String.valueOf(value);
        }
        return strValue;
    }


}
